﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;

namespace SharpSoft.WPF
{
    /// <summary>
    /// 以AOP方式调用函数时，总是在UI线程上执行方法。AOP调用方式详见<see cref="AOPHelper"/>。
    /// </summary>
    public class AlwaysRunOnUIThreadAttribute : AOPMethodAttribute
    {
        protected override object RunMethod(params object[] paras)
        {
            if (ContextInstance is DispatcherObject dobj)
            {
                if (!dobj.CheckAccess())
                {
                   return dobj.Dispatcher.Invoke(delegate {
                       return ContextMethodInfo.Invoke(ContextInstance, paras);
                    });
                }
                else
                {
                    return base.RunMethod(paras);
                }
            }
            else
            {
                throw new NotSupportedException(nameof(AlwaysRunOnUIThreadAttribute)+ " just allow use by DispatcherObject's method.");
            }

        }
    }
}
